package ua.maxicash.controller;

import org.springframework.web.bind.annotation.ResponseBody;
import ua.maxicash.service.AppService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import ua.maxicash.exceptions.NoSuchEmailInSystemException;
import ua.maxicash.service.ConfirmationService;

@Controller
public class RecoveryController {

    private static final Logger logger = Logger.getLogger(RecoveryController.class);

    @Autowired
    ConfirmationService confirmationService;

    @Autowired
    AppService appService;

    @RequestMapping("/recovery/remindPass")
    public String remindPass() {
        return "remindPassword";
    }

    @RequestMapping("/recovery/sendPassword")
    @ResponseBody
    public String sendPass(@RequestParam String email) {
        try {
            confirmationService.recoverPassword(email);
        } catch (NoSuchEmailInSystemException e) {
            logger.error(e);
            return "{ \"isOk\" : false }";
        }
        return "{ \"isOk\" : true }";

    }

    @RequestMapping("/recovery/{email}/{idRecovery}")
    public String changePassForm(@PathVariable String email, @PathVariable Long idRecovery, Model model) {
        if (confirmationService.isInRecoveryMap(email, idRecovery)) {
            model.addAttribute(appService.getSystemUserByEmail(email));
            return "recoveryPage";
        } else {
            return "error";
        }

    }

    @RequestMapping("/recovery/password")
    @ResponseBody
    public String postNewPassword(@RequestParam String email, @RequestParam String newPass, Model model) {

        confirmationService.changePassword(newPass,appService.getSystemUserByEmail(email));
        return "{ \"isOk\" : true }";

    }


}
